from django.contrib import admin
from django.utils.html import format_html
from .models import Order, OrderItem, OrderStatusHistory


class OrderItemInline(admin.TabularInline):
    """订单项目内联编辑"""
    model = OrderItem
    extra = 0
    readonly_fields = ('total_price',)
    fields = ('product', 'quantity', 'unit_price', 'total_price')


class OrderStatusHistoryInline(admin.TabularInline):
    """订单状态历史内联显示"""
    model = OrderStatusHistory
    extra = 0
    readonly_fields = ('created_at',)
    fields = ('from_status', 'to_status', 'reason', 'operator', 'created_at')


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    """订单管理"""
    list_display = (
        'order_number', 'user', 'status', 'payment_method',
        'total_amount', 'shipping_name', 'created_at'
    )
    list_filter = (
        'status', 'payment_method', 'created_at',
        'paid_at', 'shipped_at', 'delivered_at'
    )
    search_fields = (
        'order_number', 'user__username', 'user__email',
        'shipping_name', 'shipping_phone'
    )
    list_editable = ('status',)
    readonly_fields = ('order_number', 'created_at', 'updated_at')
    date_hierarchy = 'created_at'

    inlines = [OrderItemInline, OrderStatusHistoryInline]

    fieldsets = (
        ('订单信息', {
            'fields': ('order_number', 'user', 'status', 'payment_method')
        }),
        ('收货信息', {
            'fields': (
                'shipping_name', 'shipping_phone',
                'shipping_address', 'shipping_postal_code'
            )
        }),
        ('价格信息', {
            'fields': ('subtotal', 'shipping_cost', 'discount_amount', 'total_amount')
        }),
        ('时间信息', {
            'fields': (
                'created_at', 'updated_at', 'paid_at',
                'shipped_at', 'delivered_at'
            )
        }),
        ('备注信息', {
            'fields': ('notes', 'admin_notes'),
            'classes': ('collapse',)
        }),
    )


@admin.register(OrderItem)
class OrderItemAdmin(admin.ModelAdmin):
    """订单项目管理"""
    list_display = (
        'order', 'product', 'product_name', 'quantity',
        'unit_price', 'total_price'
    )
    list_filter = ('order__status', 'product__category')
    search_fields = (
        'order__order_number', 'product__name',
        'product_name'
    )
    readonly_fields = ('total_price', 'product_name', 'product_image')


@admin.register(OrderStatusHistory)
class OrderStatusHistoryAdmin(admin.ModelAdmin):
    """订单状态历史管理"""
    list_display = (
        'order', 'from_status', 'to_status',
        'operator', 'created_at'
    )
    list_filter = ('from_status', 'to_status', 'created_at')
    search_fields = ('order__order_number', 'reason')
    readonly_fields = ('created_at',)
    date_hierarchy = 'created_at'
